package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private UserDao userDao;

    @Override
    public void add(Role role,Integer[] permissionIds, Integer[] userIds, Integer[] menuIds) {
        //向角色表添加数据
        roleDao.add(role);
        //获取新添加的角色的id
        Integer id = role.getId();
        //向permission中间表插入数据
        List permission = array2List(id,permissionIds);
        permissionDao.add(permission);
        //向user中间表插入数据
        List user = array2List(id, userIds);
        userDao.add(user);
        //向menu中间表插入数据
        List menu = array2List(id, menuIds);
        menuDao.add(menu);
    }

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public void delete(Integer id) {
        //删除中间表数据
        roleDao.deleteRolePermission(id);
        roleDao.deleteRoleUser(id);
        roleDao.deleteRoleMenu(id);
        //删除role表数据
        roleDao.delete(id);
    }

    @Override
    public Role findById(Integer id) {
        //分别查询出角色关联到的数据
        Role role= roleDao.findById(id);
        return role;
    }

    @Override
    public void update(Role role, Integer[] permissionIds, Integer[] userIds, Integer[] menuIds) {
        //修改角色表数据
        roleDao.update(role);
        //获取roleid
        Integer role_id = role.getId();
        //修改权限角色中间表数据
        permissionDao.deleteByRoleId(role_id);
        List permission = array2List(role_id, permissionIds);
        permissionDao.add(permission);
        //修改角色用户中间表
        userDao.deleteByRoleId(role_id);
        List user = array2List(role_id, userIds);
        userDao.add(user);
        //修改角色菜单中间表
        menuDao.deleteByRoleId(role_id);
        List menu = array2List(role_id, menuIds);
        menuDao.add(menu);
    }

    public List array2List(Integer id,Integer[] array){
        List<Map> lists=new ArrayList<>();
        if(array!=null && array.length>0){
            for (Integer integer : array) {
                Map map=new HashMap();
                map.put("role_id",id);
                map.put("permission_id",integer);
                lists.add(map);
            }
            return lists;
        }

        return null;
    }
}
